package com.data.migration.vo;

import com.data.migration.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Peter on 2018/12/7.
 */
public class DBMetadata {
    private static final Logger logger = LoggerFactory.getLogger(DBMetadata.class);
    public static Map<String, Table> T = new HashMap<>();
    public static Map<String, Table> A = new HashMap<>();
    public static List<String> prepareSqls = new ArrayList<>();// A版添加两个列，app_type和t_id(青少版数据的id)

    static{
        initDBMetadata();// 生成数据库元数据
    }
    // 生成数据库元数据
    public static void initDBMetadata() {
        initDBMetadata_T();
        initDBMetadata_A();
    }

    public static void initDBMetadata_T() {
        try {
            logger.info("---- 初始化数据库元数据：青少版 ----");
            Connection conn = DBUtil.getConn("T");
            PreparedStatement pstmt = conn.prepareStatement("show tables from `waijiaojun-teenager`");
            ResultSet resultSet = pstmt.executeQuery();
            int i = 0;
            while (resultSet.next()) {
                String tableName = resultSet.getString(1);
                //logger.info(++i + " " + tableName);
                Table table = new Table(tableName);
                table.setColumns(findColumns(conn, tableName));
                T.put(tableName, table);
            }
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static void initDBMetadata_A() {
        try {
            // 初始化数据库元数据：A版
            logger.info("---- 初始化数据库元数据：A版 ----");
            Connection conn = DBUtil.getConn("A");
            PreparedStatement pstmt = conn.prepareStatement("show tables from `waijiaojun4.5.0`");
            ResultSet resultSet = pstmt.executeQuery();
            int i_A = 0;
            while (resultSet.next()) {
                String tableName = resultSet.getString(1);
                //logger.info(++i_A + " " + tableName);
                Table table = new Table(tableName);
                table.setColumns(findColumns(conn, tableName));
                A.put(tableName, table);
            }
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static List<Column> findColumns(Connection conn, String tableName) throws SQLException {
        PreparedStatement pstmt = conn.prepareStatement("show columns from " + tableName);
        ResultSet resultSet = pstmt.executeQuery();
        List<Column> columns = new ArrayList<>();
        while (resultSet.next()) {
            String columnName = resultSet.getString(1);
            String columnType = resultSet.getString(2);
            Column column = new Column(columnName, columnType);
            //logger.info(column.toString());
            columns.add(column);
        }
        return columns;
    }



}
